<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue"
import { SelectData, TreeData, UploadUrl } from "@/api/common/common"
import { deleteTableDataApi, getTableDataApi, saveTableDataApi } from "@/api/course/course"
import { getSelectDataApi } from "@/api/course/instructor"
import { getLessonDataApi, saveLessonDataApi } from "@/api/course/lesson"
import { getTreeDataApi } from "@/api/course/classify"
import { type TableData, type CreateOrUpdateTableRequestData } from "@/api/course/types/course"
import { type CreateOrUpdateLessonRequestData } from "@/api/course/types/lesson"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox, UploadProps } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"
import { getToken } from "../../utils/cache/cookies"

defineOptions({
  // 命名当前组件
  name: "examIndex"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const token = getToken()
const headers = { authorization: token }

//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateTableRequestData = {
  id: 0,
  title: "",
  cid1: 0,
  cid2: 0,
  type: 20,
  is_use: 10,
  hour_num: 0,
  intro: "",
  detail: "",
  instructor_ids: undefined,
  image_url: ""
}

const DEFAULT_LESSON_DATA: CreateOrUpdateLessonRequestData = {
  id: 0,
  title: "",
  course_id: 0,
  chapter_id: 0,
  is_use: 10,
  sort_num: 0,
  intro: "",
  video_url: ""
}
const dialogVisible = ref<boolean>(false)
const lessonVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateTableRequestData>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<CreateOrUpdateTableRequestData> = {
  cid2: [{ required: true, trigger: "change", message: "请选择课程分类" }],
  title: [{ required: true, trigger: "blur", message: "请输入课程名称" }]
}

const classifyData = ref<TreeData[]>([])
const instructorData = ref<SelectData[]>([])

const lessonRef = ref<FormInstance | null>(null)
const lessonFormData = ref<CreateOrUpdateLessonRequestData>(cloneDeep(DEFAULT_LESSON_DATA))
const lessonRules: FormRules<CreateOrUpdateLessonRequestData> = {
  title: [{ required: true, trigger: "blur", message: "请输入视频内容标题" }],
  course_id: [{ required: true, trigger: "blur", message: "课程不能为空" }],
  video_url: [{ required: true, trigger: "blur", message: "视频不能为空" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    console.log(formData.value)
    saveTableDataApi(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const lessonCreateOrUpdate = () => {
  lessonRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    console.log(lessonFormData.value)
    saveLessonDataApi(lessonFormData.value)
      .then(() => {
        ElMessage.success("操作成功")
        lessonVisible.value = false
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}

const resetLessonForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
//#endregion

//根据根据类型跳转到内容页面
const toChapter = (row: TableData) => {
  lessonFormData.value.course_id = row.id
  if (row.type == 20) {
    getLessonDataApi({ course_id: row.id }).then((data) => {
      console.log(data)
      if (data.length > 0) {
        lessonFormData.value = data[0]
      }
      lessonVisible.value = true
    })
  } else {
    router.push({ name: "courseChapter", query: { cid: row.id, title: row.title } })
    // ElMessage.warning("章节课程暂未开放")
  }
}
//#region 删
const handleDelete = (row: TableData) => {
  ElMessageBox.confirm(`正在删除课程：${row.title}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTableDataApi({ id: row.id }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const handleUpdate = (row: TableData) => {
  dialogVisible.value = true
  formData.value = cloneDeep(row)
}
//#endregion

//#region 查
const tableData = ref<TableData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  keyword: "",
  phone: ""
})
const getTableData = () => {
  loading.value = true
  getTableDataApi({
    page: paginationData.currentPage,
    keyword: searchData.keyword || undefined
  })
    .then((data) => {
      paginationData.total = data.total
      tableData.value = data.items
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

const handleImageSuccess: UploadProps["onSuccess"] = (res) => {
  console.log(res)
  formData.value.image_url = res.body.url
}

const beforeImageUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(rawFile.type)
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("上传的图片只支持JPG/PNG格式!")
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("上传的图片大小不能超过2MB!")
    return false
  }
  return true
}

const handleVideoSuccess: UploadProps["onSuccess"] = (res) => {
  console.log(res)
  lessonFormData.value.video_url = res.body.url
}

const beforeVideoUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(rawFile.type)
  if (rawFile.type !== "video/mp4") {
    ElMessage.error("上传的视频必须是MP4格式!")
    return false
  } else if (rawFile.size > 1 * 1024 * 1024 * 1024) {
    ElMessage.error("上传的视频不能超过1GB!")
    return false
  }
  return true
}

import type { UploadInstance, UploadRawFile } from "element-plus"
import { genFileId } from "element-plus"
import router from "@/router"

const videoUpload = ref<UploadInstance>()
const handleExceed: UploadProps["onExceed"] = (files) => {
  videoUpload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  videoUpload.value!.handleStart(file)
}

const props = {
  expandTrigger: "hover" as const
}

const handleChange = (value: any) => {
  formData.value.cid1 = value[0]
  formData.value.cid2 = value[1]
}

onMounted(() => {
  getTreeDataApi().then((data) => {
    classifyData.value = data
  })

  getSelectDataApi().then((data) => {
    instructorData.value = data
  })
})

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="keyword" label="关键字">
              <el-input v-model="searchData.keyword" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button type="danger" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增课程</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" border>
          <el-table-column prop="image_url" width="160" label="课程封面" align="center">
            <template #default="scope">
              <el-image
                style="width: 120px; height: 120px; background-color: #efefef"
                :src="scope.row.image_url == '' ? 'https://img.yzcdn.cn/vant/cat.jpeg' : scope.row.image_url"
                fit="contain"
              />
            </template>
          </el-table-column>
          <el-table-column prop="title" label="课程信息" align="left">
            <template #default="scope">
              <div class="name">{{ scope.row.title }}</div>
              <div>分类：{{ scope.row.cid1_title }} / {{ scope.row.cid2_title }}</div>
              <div>类型：{{ scope.row.type == 20 ? "单视频课程" : "章节课程" }} | 课时：{{ scope.row.hour_num }}</div>
              <div>
                讲师：
                <span
                  style="display: inline-block; margin-right: 10px"
                  v-for="item in scope.row.instructors"
                  :key="item.id"
                >
                  {{ item.name }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.is_use == 10" type="success" effect="plain">启用</el-tag>
              <el-tag v-else type="danger" effect="plain">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="240" align="center">
            <template #default="scope">
              <el-button type="warning" size="small" bg @click="toChapter(scope.row)">
                {{ scope.row.type == 20 ? "视频内容" : "章节内容" }}
              </el-button>
              <el-button type="primary" size="small" bg @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" size="small" bg @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id === undefined ? '新增课程' : '修改课程'"
      @closed="resetForm"
      width="800px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="top">
        <el-row>
          <el-col :span="7">
            <el-form-item prop="image_url" label="课程图片">
              <el-upload
                class="avatar-uploader"
                :action="UploadUrl"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                :before-upload="beforeImageUpload"
              >
                <img v-if="formData.image_url" :src="formData.image_url" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="17">
            <el-form-item prop="cid2" label="课程分类">
              <el-cascader
                :options="classifyData"
                :model-value="[formData.cid1, formData.cid2]"
                :props="props"
                @change="handleChange"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item prop="title" label="课程名称">
              <el-input v-model="formData.title" placeholder="请输入课程名称" />
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item prop="type" label="课程类型" required>
                  <el-select v-model="formData.type" placeholder="选择类型">
                    <el-option label="章节课程" :value="10" />
                    <el-option label="单视频课程" :value="20" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11" :offset="1">
                <el-form-item prop="is_use" label="状态" required>
                  <el-select v-model="formData.is_use" placeholder="选择状态">
                    <el-option label="启用" :value="10" />
                    <el-option label="禁用" :value="20" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-form-item prop="intro" label="课程介绍">
          <el-input type="textarea" v-model="formData.intro" :rows="4" placeholder="请输入课程介绍" />
        </el-form-item>
        <el-form-item prop="instructor_ids" label="课程讲师">
          <el-select v-model="formData.instructor_ids" multiple placeholder="请选择课程讲师">
            <el-option v-for="item in instructorData" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
    <!-- 视频内容谈层 -->
    <el-dialog v-model="lessonVisible" title="修改视频内容" @closed="resetLessonForm" width="50%">
      <el-form ref="lessonRef" :model="lessonFormData" :rules="lessonRules" label-width="100px" label-position="top">
        <el-form-item prop="title" label="内容名称" required>
          <el-input v-model="lessonFormData.title" placeholder="请输入内容名称" />
        </el-form-item>
        <el-form-item prop="intro" label="内容介绍">
          <el-input type="textarea" v-model="lessonFormData.intro" :rows="3" placeholder="请输入内容介绍" />
        </el-form-item>
        <el-form-item prop="video_url" label="内容视频" required>
          <el-upload
            ref="videoUpload"
            :action="UploadUrl"
            :limit="1"
            :headers="headers"
            :on-success="handleVideoSuccess"
            :before-upload="beforeVideoUpload"
            :on-exceed="handleExceed"
            :show-file-list="false"
            style="width: 100%"
          >
            <el-button type="primary" style="margin-bottom: 10px"> 上传视频 </el-button>
          </el-upload>
          <el-input v-model="lessonFormData.video_url" placeholder="请输入视频链接或上传视频" />
        </el-form-item>
        <el-form-item prop="is_use" label="状态" required>
          <el-select v-model="lessonFormData.is_use" placeholder="选择状态">
            <el-option label="启用" :value="10" />
            <el-option label="禁用" :value="20" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="lessonVisible = false">取消</el-button>
        <el-button type="primary" @click="lessonCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader .avatar {
  width: 190px;
  height: 190px;
  display: block;
}

.name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 190px;
  height: 190px;
  text-align: center;
}
</style>
